package com.sskj.mine.ui.activity;


import android.Manifest;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.ImageUtil;
import com.sskj.common.util.ImgUtil;
import com.sskj.common.util.PermissionTipUtil;
import com.sskj.common.util.SPUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.SPConfig;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.CopyUtil;
import com.sskj.mine.R;
import com.sskj.mine.R2;
import com.sskj.mine.bean.QRCodeBean;
import com.sskj.mine.component.DaggerUserDataComponent;
import com.sskj.mine.presenter.SpreadActivityPresenter;
import com.tbruyelle.rxpermissions2.RxPermissions;

import javax.inject.Inject;

import butterknife.BindView;

@Route(path = RConfig.MINE_SPREAD)//我的推广
public class SpreadActivity extends BaseActivity<SpreadActivityPresenter> {
    @BindView(R2.id.ivQRCode)
    ImageView ivQRCode;
    @BindView(R2.id.tvInviteUrl)
    TextView tvInviteUrl;
    @BindView(R2.id.tvCopy)
    TextView tvCopy;
    private UserData userData;
    @Inject
    UserViewModel userViewModel;

    @Override
    protected int getLayoutResId() {
        return R.layout.mine_activity_spread;
    }

    @Override
    public SpreadActivityPresenter getPresenter() {
        return new SpreadActivityPresenter();
    }

    @Override
    protected void initView() {
        setTitle(getString(R.string.mine_spread_title));
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
        });
    }

    @Override
    protected void initData() {
        mPresenter.getSpreadCode(SPUtil.get(SPConfig.ID, ""));
    }

    public void updateUI(QRCodeBean qrCodeBean) {
        ImageUtil.setImage(qrCodeBean.getCodeUrlImg(), ivQRCode);
        tvInviteUrl.setText(qrCodeBean.getCodeUrl());
        ClickUtil.click(tvCopy, () -> {  // 保存Code值
            CopyUtil.copy(qrCodeBean.getCodeUrl());
        });
        ivQRCode.setOnLongClickListener(v -> {
            new RxPermissions(SpreadActivity.this)
                    .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe(isGrant -> {
                        if (isGrant) {
                            ImgUtil.saveImageToGallery(SpreadActivity.this, v);
                        } else {
                            PermissionTipUtil.tip(SpreadActivity.this, getString(R.string.mine_spread_5));
                        }
                    });
            return false;
        });
    }
}
